package com.ruoyi.framework.web.service;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.aliyun.MySms;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 短信验证码服务
 */
@Service
public class SmsService {

//    @Autowired private MySms smsUtil;
    @Autowired private RedisCache redisCache;
    @Autowired private ISysUserService userService;

    /**
     * 发送验证码
     * @param phone      手机号
     * @param register 是否校验用户
     */
    public String sendSmsCode(String phone, boolean register) {
        //校验用户是否存在
        SysUser user = userService.selectUserByPhone(phone);
        if (register && ObjectUtil.isNotEmpty(user)) {//注册
            throw new ServiceException("用户手机号已注册，请登录！");
        }
        if (!register && ObjectUtil.isEmpty(user)){//登录
            throw new ServiceException("用户手机号未注册，请注册");
        }
        String uuid = UUID.randomUUID().toString(true);
        //判断验证码已经存在
        String key = Constants.SMS_CAPTCHA_CODE_KEY + uuid;
        if (ObjectUtil.isNotEmpty(redisCache.getCacheObject(key))) {
            throw new ServiceException("您的验证码还在有效期，请勿重复提交！");
        }
        //生成6位验证码
        String code = RandomUtil.randomNumbers(6);
        //发送
//        if (!smsUtil.sendPhoneCode(phone, code).getHttpResponse().isSuccess()) {
//            throw new ServiceException("发送失败");
//        }
        //发送成功后存入redis  一分钟过期时间
        redisCache.setCacheObject(key,new JSONObject().set("code",code).set("mobile",phone), 5, TimeUnit.MINUTES);

        // 新增：记录日志信息到 List
        JSONObject record = new JSONObject()
                .set("phone", phone)
                .set("code", code)
                .set("sendTime", System.currentTimeMillis());
        redisCache.setCacheList("sms:jilu", record.toString());

        return uuid;
    }

    /**
     * 检查手机号注册
     */
    public void checkSmsCode(String mobile, String inputCode, String uuid) {
        String verifyKey = Constants.SMS_CAPTCHA_CODE_KEY + uuid;
        JSONObject data = redisCache.getCacheObject(verifyKey);
        //redisCache.deleteObject(verifyKey);
        if (StrUtil.isBlank(inputCode)) {
            throw new ServiceException("验证码不能为空");
        }
        if (ObjectUtil.isEmpty(data)) {
            throw new ServiceException("验证码失效");
        }
        if (!mobile.equals(data.getStr("mobile"))) {
            throw new ServiceException("手机号码不一致");
        }
        if (!inputCode.equals(data.getStr("code"))) {
            throw new ServiceException("验证码错误");
        }
    }
}
